<?php

/*
 * APP公共控制器
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class PublicController extends AppBaseC {

    //用户登录
    public function actionLogin() {
        $sign = Yii::app()->request->getParam('sign');
        //版本
        $version = Yii::app()->request->getParam('version');
        //平台  iOS|Android
        $platform = Yii::app()->request->getParam('platform');
        //授权信息 array('bind_type'=>aqq,'openid','token','regdate'=>(expires_in+time)...)
        $oauth = Yii::app()->request->getParam('oauth');
        $model = MembersAccessModel::model();
        //解密
        switch ($platform) {
            case 'iOS':
                $sign = AppEncrypt::ios($sign, 'DECODE');
                break;
            case 'Android':
                $sign = AppEncrypt::android($sign, 'DECODE');
                break;
            default:
                $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1001));
                break;
        }
        if (empty($sign)) {
            $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1002));
        } else {
            $data = json_decode($sign, true);
        }
        if (empty($data['username'])) {
            $this->ajaxReturn(array('info' => '用户名为空！', 'error_code' => 1003));
        }
        $data['username'] = urldecode($data['username']);
        if (empty($data['password'])) {
            $this->ajaxReturn(array('info' => '密码不能为空！', 'error_code' => 1004));
        }
        //检查是否第三方登录
        if (!empty($oauth) && is_array($oauth)) {
            $bindInfo = MembersOauthModel::model()->isBind($oauth['bind_type'], $oauth);
            if (!empty($bindInfo)) {
                $userInfo = Yii::app()->user->getLocalUser((int) $bindInfo['uid']);
                $return = $model->login($userInfo['username']);
                if ($return !== false) {
                    $this->ajaxReturn(array('status' => true, 'token' => $return['token'], 'expired_time' => $return['expired_time'], 'uid' => $return['uid'], 'username' => $data['username']));
                } else {
                    $this->ajaxReturn(array('info' => $model->getOneError() ? $model->getOneError() : "账号或密码错误！", 'error_code' => 1010));
                }
            } else {
                $this->ajaxReturn(array('error_code' => 1125, 'info' => "账户未进行绑定,请先绑定账户后登录"));
            }
        } else {
            $return = $model->login($data['username'], $data['password']);
            if (!empty($return)) {
                $this->ajaxReturn(array('status' => true, 'token' => $return['token'], 'expired_time' => $return['expired_time'], 'uid' => $return['uid'], 'username' => $data['username']));
            } else {
                $this->ajaxReturn(array('info' => $model->getOneError() ? $model->getOneError() : "账号或密码错误！", 'error_code' => 1010));
            }
        }
    }

    //已有本地账户进行第三方登录账户绑定登录
    public function actionBindLogin() {
        $sign = Yii::app()->request->getParam('sign');
        //版本
        $version = Yii::app()->request->getParam('version');
        //平台  iOS|Android
        $platform = Yii::app()->request->getParam('platform');
        //授权信息 array('bind_type'=>aqq,'openid','token','regdate'=>(expires_in+time)...)
        $oauth = Yii::app()->request->getParam('oauth');
        //解密
        switch ($platform) {
            case 'iOS':
                $sign = AppEncrypt::ios($sign, 'DECODE');
                break;
            case 'Android':
                $sign = AppEncrypt::android($sign, 'DECODE');
                break;
            default:
                $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1001));
                break;
        }
        if (empty($sign)) {
            $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1002));
        } else {
            $data = json_decode($sign, true);
        }
        if (empty($data['username'])) {
            $this->ajaxReturn(array('info' => '用户名为空！', 'error_code' => 1003));
        }
        $data['username'] = urldecode($data['username']);
        if (empty($data['password'])) {
            $this->ajaxReturn(array('info' => '密码不能为空！', 'error_code' => 1004));
        }
        if (empty($oauth) && !is_array($oauth)) {
            $this->ajaxReturn(array('status' => false, 'info' => '授权信息错误，请重新授权登录！'));
        }
        //根据用户名,密码获取user数组
        $user = Yii::app()->user->getLocalUser($data['username'], $data['password']);
        if (empty($user)) {
            $this->ajaxReturn(array('status' => false, 'info' => "账号或密码错误，绑定账号失败"));
        }
        $MembersOauth = new MembersOauthModel();
        $model = MembersAccessModel::model();
        //验证该UID 是否已经绑定
        if ($MembersOauth->isUserBind($oauth['bind_type'], (int) $user['uid'])) {
            $this->ajaxReturn(array('status' => false, 'info' => '该授权账号已经绑定其他账户,请确认!'));
        }
        if ($MembersOauth->addBind($oauth['bind_type'], $oauth, $user['uid'])) {
            $return = $model->login($user['username']);
            if ($return !== false) {
                $this->ajaxReturn(array('status' => true, 'token' => $return['token'], 'expired_time' => $return['expired_time'], 'uid' => $return['uid'], 'username' => $data['username']));
            } else {
                $this->ajaxReturn(array('status' => false, 'info' => $model->getOneError() ? $model->getOneError() : "登录失败！", 'error_code' => 1010));
            }
        } else {
            $this->ajaxReturn(array('status' => false, 'info' => $MembersOauth->getOneError() ? $MembersOauth->getOneError() : "绑定账号失败"));
        }
    }

    //注册
    public function actionReg() {
        //类型
        $kind = (int) Yii::app()->request->getParam('kind');
        //密文 {'username':'','password':''}
        $sign = Yii::app()->request->getParam('sign');
        //版本
        $version = Yii::app()->request->getParam('version');
        //平台  iOS|Android
        $platform = Yii::app()->request->getParam('platform');
        //授权信息 array('bind_type'=>aqq,'openid','token','regdate'=>(expires_in+time)...)
        $oauth = Yii::app()->request->getParam('oauth');
        //手机号
        $phone = trim(Yii::app()->request->getParam('phone'));
        //验证码
        $code = Yii::app()->request->getParam('code');
        $model = new MembersModel;
        if ($kind == 0) {
            if (empty($phone)) {
                $this->ajaxReturn(array('status' => 0, 'info' => '手机号不能为空'));
            }
            $oldphone = MembersModel::getByPhone($phone);
            if (!empty($oldphone)) {
                $this->ajaxReturn(array('status' => 0, 'info' => '该手机号已经被注册，请用别的手机号注册'));
            }
            if (SnsVerification::getInstance()->verification($code, $phone, 'appphone') !== true) {
                $this->ajaxReturn(array('status' => 0, 'info' => SnsVerification::getInstance()->getError() ? SnsVerification::getInstance()->getError() : '验证失败',));
            }
        }
        //解密
        switch ($platform) {
            case 'iOS':
                $sign = AppEncrypt::ios($sign, 'DECODE');
                break;
            case 'Android':
                $sign = AppEncrypt::android($sign, 'DECODE');
                break;
            default:
                $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1001));
                break;
        }
        if (empty($sign)) {
            $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1002));
        } else {
            $data = json_decode($sign, true);
        }
        if (empty($data['username'])) {
            $this->ajaxReturn(array('info' => '用户名为空！', 'error_code' => 1003));
        }
        $data['username'] = urldecode($data['username']);
        if (empty($data['password'])) {
            $this->ajaxReturn(array('info' => '密码为空！', 'error_code' => 1004));
        }
        $model->setValidators(array(
            array('email', 'required', 'message' => '邮箱不能为空！|1005'),
            array('email', 'unique', 'message' => '您输入的邮箱已被使用！|1006'),
            array('username', 'unique', 'allowEmpty' => false, 'message' => '该用户名已经存在！|1008',),
            array('email', 'email', 'message' => '您输入的邮箱地址无效！|1007'),
            array('password', 'length', 'tooShort' => '密码不能低于6位！', 'min' => 6),
            array('password', 'required', 'message' => '密码不能为空！|1004'),
            array('group_id,type,status,regip,regdate,lastloginip,lastlogintime,kind', 'safe'),
            array('phone', 'safe'),
            array('repassword', 'compare', 'compareAttribute' => 'password', 'message' => '两次输入密码不一致！|1009'),
        ));
        $model->attributes = array(
            'username' => $data['username'],
            'password' => $data['password'],
            'repassword' => $data['password'],
            'kind' => $kind,
            'email' => $data['email'],
            'phone' => $phone,
        );
        if (!$model->validate()) {
            $message = $model->getOneError() ? $model->getOneError() : '注册信息有误！|1011';
            $message = explode('|', $message);
            $this->ajaxReturn(array('info' => $message[0], 'error_code' => $message[1]));
        } else {
            $data['status'] = 1;
            $data['kind'] = $kind;
            $data['repassword'] = $data['password'];
            $data['phone'] = $phone;
            //传参注册
            UserRegister::getInstance()->data($data);
            $newUid = UserRegister::getInstance()->register();
            if ($newUid) {
                //第三方授权注册绑定
                if (!empty($oauth) && is_array($oauth)) {
                    //验证该UID 是否已经绑定
                    if (!$MembersOauth->isUserBind($oauth['bind_type'], (int) $newUid)) {
                        $MembersOauth->addBind($oauth['bind_type'], $oauth, $newUid);
                    }
                }
                $this->ajaxReturn(array('status' => 1, 'info' => "注册成功！",));
            }
        }
        $this->ajaxReturn(array('status' => 0, 'info' => "注册失败！", 'error_code' => 1100));
    }

    //发送手机验证码
    public function actionSendcode() {
        $moblie = Yii::app()->request->getParam('phone');
        $platform = Yii::app()->request->getParam('platform');
        switch ($platform) {
            case 'iOS':
                $moblie = AppEncrypt::ios($moblie, 'DECODE');
                break;
            case 'Android':
                $moblie = AppEncrypt::android($moblie, 'DECODE');
                break;
            default:
                $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1001));
                break;
        }
        if (empty($moblie)) {
            $this->ajaxReturn(array('status' => 0, 'info' => "手机号不能为空!"));
        } else {
            $moblie = json_decode($moblie, true);
        }
        $key = md5(GuestDataModel::model()->getForwardedForIp() . $moblie);
        if (Yii::app()->cache->get($key)) {
            $this->ajaxReturn(array('status' => 0, 'info' => "请在60秒后在发送",));
        }
        if (SnsVerification::getInstance()->send($moblie['phone'], 'appphone')) {
            Yii::app()->cache->set($key, 1, 60);
            $this->ajaxReturn(array('status' => 1, 'info' => "短信验证码已经发送！",));
        } else {
            $this->ajaxReturn(array('status' => 0, 'info' => SnsVerification::getInstance()->getError() ? SnsVerification::getInstance()->getError() : "验证码发送失败！",));
        }
    }

    //商品举报
    public function actionJb() {
        $model = new PunishModel();
        $data['uid'] = (int) Yii::app()->request->getParam('uid');
        $data['username'] = Yii::app()->request->getParam('username');
        if ($data['uid'] == 0) {
            $data['username'] = '游客';
        } else {
            $userInfoObj = MembersModel::model()->findByPk($data['uid']);
            $data['username'] = $userInfoObj->username;
        }
        $data['good_id'] = Yii::app()->request->getParam('good_id');
        if (empty($data['good_id'])) {
            $this->ajaxReturn(array('info' => '请确认举报商品!', 'error_code' => 1020));
        }
        $data['goods_name'] = Yii::app()->request->getParam('good_name');
        $GoodsModel = new GoodsModel();
        $GoodsModelobj = $GoodsModel->find($GoodsModel->where(array('goods_id' => $data['good_id'])));
        $data['goods_name'] = $GoodsModelobj->goods_name;
        $data['type'] = Yii::app()->request->getParam('type');
        if (empty($data['type'])) {
            $this->ajaxReturn(array('info' => '请填写举报内容!', 'error_code' => 1107));
        }
        $data['cause'] = Yii::app()->request->getParam('cause');
        $data['add_time'] = Yii::app()->request->getParam('add_time');
        //$model->setValidators($model->rules);
        $model->attributes = $data;
        if ($model->validate() && $model->save()) {
            $this->ajaxReturn(array('status' => 1, 'info' => "提交成功,我们会尽快确认"));
        } else {
            $this->ajaxReturn(array('status' => 0, 'info' => "输入有误,请重新举报", 'error_code' => 1022));
        }
    }

    /**
     * 启动页图片接口
     */
    public function actionStartpic() {
        $platform = Yii::app()->request->getParam('platform');
        $model = new AppStartpicModel();
        switch ($platform) {
            case 'iOS':
                $criteria = $model->where(array('platform' => 1, 'order' => 'uploadtime desc'));
                $data = $model->findAll($criteria);
                $data = $data[0]->attributes;
                break;
            case 'Android':
                $criteria = $model->where(array('platform' => 0, 'order' => 'uploadtime desc'));
                $data = $model->findAll($criteria);
                $data = $data[0]->attributes;
                break;
            default:
                $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1001));
                break;
        }
        if (!empty($data)) {
            $this->ajaxReturn(array('status' => 1, 'startpic' => $data['filepath'], 'url' => $data['url'], 'title' => $data['title'] ? $data['title'] : '活动详情'));
        } else {
            $this->ajaxReturn(array('status' => 0, 'error_code' => 1105));
        }
    }

    /**
     * 天猫滚动图片接口
     */
    public function actionTmpic() {
        $data = array(
            0 => array('img' => '', 'url' => ''),
            1 => array('img' => '', 'url' => ''),
        );
        if (!empty($data[0]['img'])) {
            $this->ajaxReturn(array('status' => 1, 'rollpic' => $data));
        } else {
            $this->ajaxReturn(array('status' => 0, 'error_code' => 1105));
        }
    }

    /**
     * 首页滚动图片接口
     */
    public function actionRollpic() {
        $platform = Yii::app()->request->getParam('platform');
        $model = new AppStartpicModel();
        switch ($platform) {
            case 'iOS':
                $criteria = $model->where(array('platform' => 3, 'order' => 'uploadtime desc', 'limit' => 4));
                $datap = $model->findAll($criteria);
                $data = array();
                foreach ($datap as $t => $ui) {
                    $data[$t]['img'] = $ui->filepath;
                    $data[$t]['url'] = $ui->url;
                }
                break;
            case 'Android':
                $criteria = $model->where(array('platform' => 2, 'order' => 'uploadtime desc', 'limit' => 4));
                $datap = $model->findAll($criteria);
                $data = array();
                foreach ($datap as $t => $ui) {
                    $data[$t]['img'] = $ui->filepath;
                    $data[$t]['url'] = $ui->url;
                }
                break;
            default:
//                $this->ajaxReturn(array('info' => '请求非法！', 'error_code' => 1001));
                $criteria = $model->where(array('platform' => 2, 'order' => 'uploadtime desc', 'limit' => 4));
                $datap = $model->findAll($criteria);
                $data = array();
                foreach ($datap as $t => $ui) {
                    $data[$t]['img'] = $ui->filepath;
                    $data[$t]['url'] = $ui->url;
                }
                break;
        }
        if (!empty($data)) {
            $this->ajaxReturn(array('status' => 1, 'rollpic' => $data));
        } else {
            $this->ajaxReturn(array('status' => 0, 'error_code' => 1105));
        }
    }

    //搜索链接
    public function actionSearch() {
        $key = Yii::app()->request->getParam('key');
        $keywords = urlencode($key);
        if (empty($keywords)) {
            $this->ajaxReturn(array('status' => 0, 'info' => '请输入搜索词', 'url' => ''));
        } else {
            $this->ajaxReturn(array('status' => 1, 'url' => 'http://s8.taobao.com/search?pid=mm_34837309_4174087_13582095&commend=all&unid=1zw&q=' . $keywords, 'info' => 'Congratulations to you !'));
        }
    }

}
